package com.leo;

import javafx.application.Application;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @ClassName Demo
 * @Description 利用绑定方式，同步改变值
 * @Author wangss
 * @date 2020.05.31 22:44
 * @Version 1.0
 */
public class Demo extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        AnchorPane an = new AnchorPane();
        an.setStyle("-fx-background-color: #fff2f2");
        Scene scene = new Scene(an);

        HBox hBox = new HBox(10);
        TextField t1 = new TextField();
        TextField t2 = new TextField();
        hBox.getChildren().addAll(t1, t2);

        VBox vBox = new VBox(10);
        vBox.getChildren().add(hBox);

        ObservableList<String> obsList = FXCollections.observableArrayList();
        SimpleListProperty<String> list = new SimpleListProperty<>(obsList);

        list.addAll("A", "B", "C", "D", "E");

        for (int i = 0; i < list.size(); i++) {
            Label label = new Label();

//            ObjectBinding<String> stringObjectBinding = list.valueAt(i);
            // 进行单向绑定
            label.textProperty().bind(list.valueAt(i));

            vBox.getChildren().add(label);
        }

        AnchorPane.setTopAnchor(vBox, 100d);
        AnchorPane.setLeftAnchor(vBox, 100d);
        an.getChildren().add(vBox);

        primaryStage.setScene(scene);
        primaryStage.setTitle("集合协同同步");
        primaryStage.setWidth(600d);
        primaryStage.setHeight(600d);
        primaryStage.setResizable(false);
        primaryStage.show();

        t2.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                String t1Text = t1.getText();
                if (null == t1Text || "".equals(t1Text)) {
                    return;
                }

                try {
                    int index = Integer.valueOf(t1Text);
                    list.set(index, t2.getText());
                } catch (Exception e) {
                    return;
                }
            }
        });
    }
}
